package Geek

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	models "backSever/modules"

	"github.com/gin-gonic/gin"
)

type GeekController struct {
}

// 登录
func (G GeekController) Login(ctx *gin.Context) {
	var params struct {
		Mobile string `json:"mobile"`
		Code   string `json:"code"`
	}

	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	fmt.Println("用户情报：", params.Mobile, params.Code)

	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{"token": "4562dada64fafc1ac"},
	})
}

// 用户信息
func (G GeekController) GetUserInfo(ctx *gin.Context) {
	// 从 Authorization 头获取token
	token := ctx.GetHeader("Authorization")

	// 或者使用 Request 对象直接获取token
	// token := ctx.Request.Header.Get("Authorization")

	// 通常格式是 "Bearer <token>"，所以可能需要去掉前缀
	if len(token) > 7 && strings.HasPrefix(token, "Bearer ") {
		token = token[7:]
	}
	fmt.Println("token", token)
	if token != "4562dada64fafc1ac" {
		fmt.Println("token失效!")
		ctx.JSON(401, gin.H{
			"error": "token失效",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{"name": "齐天大圣"},
	})
}

// 频道信息
func (G GeekController) GetChannels(ctx *gin.Context) {

	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"channels": []gin.H{
				{
					"id":         1,
					"channel_id": 1,
					"channel":    "jave",
					"value":      "jave",
				},
				{
					"id":         2,
					"channel_id": 2,
					"channel":    "react",
					"value":      "react",
				},
				{
					"id":         3,
					"channel_id": 3,
					"channel":    "vue",
					"value":      "vue",
				},
				{
					"id":         4,
					"channel_id": 4,
					"channel":    "go",
					"value":      "go",
				},
				{
					"id":         5,
					"channel_id": 5,
					"channel":    "python",
					"value":      "python",
				},
			},
		},
	})
}

// 发布还是更新
func (G GeekController) PublishOrUpdate(ctx *gin.Context) {
	GeekController := GeekController{}
	if id := ctx.Param("id"); id != "" {
		fmt.Println("发布还是更新id:", ctx.Param("id"))
		GeekController.UpArticle(ctx)
	} else {
		GeekController.Publish(ctx)
	}
}

// 发布文章
func (G GeekController) Publish(ctx *gin.Context) {
	draft := ctx.Query("draft")
	var article models.Article
	if err := ctx.ShouldBindJSON(&article); err != nil {
		fmt.Printf("JSON绑定错误: %v", err)
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}
	// article.BeforeSave()
	article.CreateArticle(&article)
	fmt.Println("draft:", draft)
	fmt.Printf("publish:%#v", article)

	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"messge": "ok",
		},
	})
}

// 上传图片
func (G GeekController) Upload(ctx *gin.Context) {
	//单文件
	file, err := ctx.FormFile("image")
	if err != nil {
		fmt.Println("FormFile err:", err)
		ctx.JSON(400, gin.H{"error": err})
		return
	}

	uploadDir := "./static/upload/"
	os.MkdirAll(uploadDir, os.ModePerm)
	filePath := filepath.Join(uploadDir, file.Filename)

	//上传文件至指定目录
	err1 := ctx.SaveUploadedFile(file, filePath)
	if err1 != nil {
		fmt.Println("SaveUploadedFile err:", err1)
		ctx.JSON(400, gin.H{"error": err1})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"url": "http://localhost/static/upload/" + file.Filename,
		},
		"message": "OK",
	})
}

// 根据id删除一条数据
func (G GeekController) DelArticleById(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	deletedArticle, err := models.Article{}.DeletelArticleById(id)
	if err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"deletedArticle": deletedArticle,
		},
		"message": "OK",
	})
}

// 修改文章
func (G GeekController) UpArticle(ctx *gin.Context) {
	var article models.Article
	if err := ctx.ShouldBindJSON(&article); err != nil {
		fmt.Printf("JSON绑定错误: %v", err)
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}
	article.Id, _ = strconv.Atoi(ctx.Param("id"))

	fmt.Println("id:", ctx.Param("id"))
	fmt.Println("更新后：", article)

	if err := article.UpdateArticle(); err != nil {
		fmt.Printf("DB更新错误: %v", err)
		ctx.JSON(400, gin.H{"error": err.Error()})
	}
	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"messge": "更新ok",
		},
	})
}

// 根据条件查询文章,没有条件则查询所有文章
func (G GeekController) QueryArticles(ctx *gin.Context) {
	var articles []models.Article
	var err error
	conditions := make(map[string]string)
	if id := ctx.Query("id"); id != "" {
		conditions["id"] = id
	}
	if status := ctx.Query("status"); status != "" {
		conditions["status"] = status
	}
	if channel_id := ctx.Query("channel_id"); channel_id != "" {
		conditions["channel_id"] = channel_id
	}

	if begin_pubdate := ctx.Query("begin_pubdate"); begin_pubdate != "" {
		if _, err := time.Parse("2006-01-02", begin_pubdate); err == nil {
			conditions["begin_pubdate"] = begin_pubdate + " 00:00:00"
		}
	}
	if end_pubdate := ctx.Query("end_pubdate"); end_pubdate != "" {
		if _, err := time.Parse("2006-01-02", end_pubdate); err == nil {
			conditions["end_pubdate"] = end_pubdate + " 23:59:59"
		}
	}

	if len(conditions) == 0 {
		articles, err = models.Article{}.GetAllArticles()
		if err != nil {
			ctx.JSON(400, gin.H{"error": err})
			return
		}
	} else {
		articles, err = models.Article{}.QueryArticlesByConditions(conditions)
		if err != nil {
			ctx.JSON(400, gin.H{"error": err})
			return
		}
	}
	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"results": articles,
		},
		"total_count": len(articles),
		"message":     "OK",
	})
}

// 获取频道对应文章count件数
func (G GeekController) ChannelIdCount(ctx *gin.Context) {
	channels := map[string]int{
		"jave":   1,
		"react":  2,
		"vue":    3,
		"go":     4,
		"python": 5,
	}

	channelCount, totalCount := models.Article{}.QueryArticlesCount(channels)
	ctx.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"results":     channelCount,
			"total_count": totalCount,
		},
		"message": "OK",
	})

}

//文章列表
/*
    const data = [
        {
            id: '8218',
            comment_count: 0,
            cover: {
                images: [], //图片url列表
            },
            like_count: 0,
            pubdate: '2019-03-11 09:00:00',
            read_count: 2,
            status: 2,
            title: 'wkwebview离线化加载h5资源解决方案'
        }
    ]

	data
		results
			id
			title
			status
		total-count
		message: ok
*/
